package com.geaosu.filesselector;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


/**
 * 文件夹/文件 列表
 */
public class FileListFragment extends Fragment {
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private ListView mListView;
    private RelativeLayout mEmptyView;

    private FileListFragmentAdapter mAdapter;
    private List<FileBean> mSingleFileList = new ArrayList<>();

    private String mPath;

    public FileListFragment(String path) {
        this.mPath = path;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
    }

    public static Fragment open(String path) {
        return new FileListFragment(path);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_file_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.mSwipeRefreshLayout);
        mListView = (ListView) view.findViewById(R.id.mListView);
        mEmptyView = (RelativeLayout) view.findViewById(R.id.mEmptyView);

        // mListView
        mListView.setAdapter(mAdapter = new FileListFragmentAdapter());
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FileBean bean = mSingleFileList.get(position);
                File file = new File(bean.getPath());
                if (file.isDirectory()) {
                    for (int i = 0; i < mSingleFileList.size(); i++) {
                        mSingleFileList.get(i).setSelect(false);
                    }
                    mAdapter.notifyDataSetChanged();
                    EventBus.getDefault().post(new DataEvent(DataEvent.Type.TO_NEXT_FOLDER, bean));
                } else {
                    bean.setSelect(!bean.isSelect());
                    mAdapter.notifyDataSetChanged();
                }
            }
        });

        // 设置刷新时要显示的颜色
        mSwipeRefreshLayout.setColorSchemeColors(
                Color.parseColor("#0000FF"),// 蓝色
                Color.parseColor("#FF0000"),// 红色
                Color.parseColor("#00FF00")// 绿色
        );
        // 设置背景
        //mSwipeRefreshLayout.setProgressBackgroundColor(Color.parseColor("#EEEEEE"));
        // 监听器
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });

        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                loadData();
            }
        });
    }

    private void loadData() {
        // 文件全路径 = 文件夹+文件名+后缀
        // file = new File(driPath + File.separator + fileName);
        File file = new File(mPath);
        File[] files = file.listFiles();

        if (files != null && files.length > 0) {
            mSingleFileList.clear();
            for (int i = 0; i < files.length; i++) {
                File sFile = files[i];
                String path = sFile.getAbsolutePath();
                String name = sFile.getName();

                FileBean fileBean = new FileBean();
                fileBean.setName(name);
                fileBean.setPath(path);
                mSingleFileList.add(fileBean);
            }
            if (mSingleFileList.size() > 0) {
                // 先把文件夹拿出来
                List<FileBean> dirList = new ArrayList<>();
                for (FileBean bean : mSingleFileList) {
                    if (new File(bean.getPath()).isDirectory()) {
                        // 过滤掉以点开头的隐藏文件夹
                        if (!bean.getName().startsWith(".")) {
                            dirList.add(bean);
                        }
                    }
                }
                // 按A-Z序列化list
                Collections.sort(dirList, new Comparator<FileBean>() {
                    @Override
                    public int compare(FileBean o1, FileBean o2) {
                        return o1.getName().compareTo(o2.getName());
                    }
                });

                // 再把文件拿出来
                List<FileBean> fileList = new ArrayList<>();
                for (FileBean bean : mSingleFileList) {
                    if (new File(bean.getPath()).isFile()) {
                        // 过滤掉以点开头的隐藏文件
                        if (!bean.getName().startsWith(".")) {
                            fileList.add(bean);
                        }
                    }
                }
                // 按A-Z序列化list
                Collections.sort(fileList, new Comparator<FileBean>() {
                    @Override
                    public int compare(FileBean o1, FileBean o2) {
                        return o1.getName().compareTo(o2.getName());
                    }
                });

                mSingleFileList.clear();
                mSingleFileList.addAll(dirList);
                mSingleFileList.addAll(fileList);
            }
        } else {
            Toast.makeText(getActivity(), "空文件夹", Toast.LENGTH_SHORT).show();
        }

        new CountDownTimer(500, 500) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                mSwipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        // 结束刷新
                        mSwipeRefreshLayout.setRefreshing(false);
                        if (mSingleFileList.size() > 0) {
                            mEmptyView.setVisibility(View.GONE);
                            mListView.setVisibility(View.VISIBLE);
                            mAdapter.replaceAll(mSingleFileList);
                        } else {
                            mListView.setVisibility(View.GONE);
                            mEmptyView.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        }.start();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    /**
     * EventBus 数据和事件分发
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DataEvent event) {

    }
}
